package org.supda.system.controller.test;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 
 * @author supda
 * @Date 2017-2-27 下午2:10:30
 * 
 * 测试websocket+stomp
 * 
 * stomp和websocket相当于http与tcp/ip
 * stomp是对websocket的包装。
 *
 *
 *@RestController 相当于以下两个注解的组合
 *
 *@Controller  
 *@ResponseBody  
 *
 *
 */
@RestController //@Controller
public class GreetingController {

	 @Autowired  
	 private SimpMessageSendingOperations simpMessageSendingOperations;  
	 
	 /*@Autowired
	 private ScheduledTask   scheduledTask;*/
	  
	 /**
	  * 第一个方法，表示服务器端可以接收客户端通过主题"/app/hello"发送过来的消息，客户端需要在主题"/topic/hello"上监听并接收服务器发回的消息。
	  * 
	  */
	@MessageMapping("/hello") //hello"为WebSocketConfig类中registerStompEndpoints()方法配置的 
    @SendTo("/topic/greetings")
    public void handle(@Header("atytopic") String topic, @Headers Map<String, Object> headers) {
		  System.out.println("connected successfully....");  
	        System.out.println(topic);  
	        System.out.println(headers);  
    }
	
    /** 
     * 这里用的是@SendToUser，这就是发送给单一客户端的标志。本例中， 
     * 客户端接收一对一消息的主题应该是“/user/” + 用户Id + “/message” ,这里的用户id可以是一个普通的字符串，只要每个用户端都使用自己的id并且服务端知道每个用户的id就行。 
     * @return 
     */  
    @MessageMapping("/message")  
    @SendToUser("/message")  
    public Greeting handleSubscribe() {  
        System.out.println("this is the @SubscribeMapping('/marco')");  
        return new Greeting("I am a msg from SubscribeMapping('/macro').");  
    }
    
    /** 
     * 发送消息使用SimpMessagingTemplete类的convertAndSend("/topic/hello", greeting);广播，
     *  和convertAndSendToUser(userId, "/message", userMessage); //一对一发送给特定用户。
     */  
    @RequestMapping(value = "/send", method = RequestMethod.GET) 
    public Greeting send() {
    	simpMessageSendingOperations.convertAndSend("/topic/message", new Greeting(" /topic/message I am a msg from SubscribeMapping('/macro')."));
       
 /*   	scheduledTask.myTest();*/
    	if(ScheduledTasks.simpMessageSendingOperations == null)
    		ScheduledTasks.simpMessageSendingOperations = simpMessageSendingOperations;
    	
    	simpMessageSendingOperations.convertAndSendToUser("1", "/message", new Greeting("I am a msg from SubscribeMapping('/macro').")); 
        return new Greeting("I am a msg from SubscribeMapping('/macro').");  
    }  
}